package ude.univ.esiag.gon.uchiha.subscriber;

import java.io.Serializable;
import java.util.Vector;

import ude.univ.esiag.gon.uchiha.operation.Operation;
import ude.univ.esiag.gon.uchiha.reader.DataReaderListener;
import ude.univ.esiag.gon.uchiha.subscriber.impl.SubscriberImpl;

public class DataReactor {
	
	private static DataReactor singleton;
	private static Vector<DataReactor> singletons;
	private static short MAXLISTNERS = 5;
	
	private Vector<DataReaderListener> listeners;
	private Semaphore semaphore;
	private SubscriberImpl subscriber;
	
	private DataReactor() {
		listeners = new Vector<DataReaderListener>();
		subscriber = new SubscriberImpl(this);
		semaphore = new Semaphore();
	}
	
	public static DataReactor newInstance(){
		if(singleton == null){
			singletons = new Vector<DataReactor>();
			singleton = new DataReactor();
		}
		if(singleton.listeners.size() >= MAXLISTNERS){
			singletons.add(singleton);
			singleton = new DataReactor();
		}
		return singleton;
	}
	
	public SubscriberImpl addListener(DataReaderListener listener){
		semaphore.stop();
		listeners.add(listener);
		semaphore.signal();
		return subscriber;
	}
	
	public void signal(Serializable obj){
		Operation op = (Operation)obj;
		semaphore.stop();
		for(int i = 0;i<listeners.size();i++){
			listeners.get(i).signal(op.getData().getTopicName());
		}
		semaphore.signal();
	}
}
